import { defineStore } from 'pinia'

// 解析 JWT token 获取过期时间
const parseJWT = (token) => {
  try {
    const payload = token.split('.')[1]
    const decoded = JSON.parse(atob(payload))
    return {
      exp: decoded.exp ? decoded.exp * 1000 : null, // JWT exp 是秒，转毫秒
      role: decoded.role, // 提取角色信息
      username: decoded.sub // 提取用户名
    }
  } catch (error) {
    console.error('解析 JWT 失败:', error)
    return null
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    token: localStorage.getItem('token') || null
  }),

  actions: {
    // 登录时调用
    setUserInfo(user, token) {
      this.userInfo = user
      this.token = token
      localStorage.setItem('userInfo', JSON.stringify(user))
      localStorage.setItem('token', token)
    },

    // 退出登录
    logout() {
      this.userInfo = null
      this.token = null
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
    },

    // 检查 token 是否过期
    checkTokenExpiry() {
      if (!this.token) return true

      const payload = parseJWT(this.token)
      if (!payload || !payload.exp) return true

      const isExpired = Date.now() > payload.exp
      if (isExpired) {
        this.logout()
        return true
      }

      return false
    },
    // 自动清理过期 token
    autoCleanExpiredToken() {
      return this.checkTokenExpiry()
    },

  },
  getters: {
    // 检查是否登录
    isLogin: (state) => {
      if (!state.token) return false

      const payload = parseJWT(state.token)
      if (!payload || !payload.exp) return false

      return Date.now() <= payload.exp
    },

    // 获取用户角色（getter 版本）
    userRole: (state) => {
      if (!state.token) return null
      const payload = parseJWT(state.token)
      return payload?.role || null
    }
  }
})
